/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package javafx191labs.ssheypak.common;

import java.beans.BeanInfo;
import java.beans.Introspector;
import java.beans.PropertyDescriptor;
import javafx191labs.ssheypak.common.data.Entity;
import javafx191labs.ssheypak.common.exception.DataInputException;


/**
 * Class for setting instance fields values.
 * Very simple realization, uses only String values.
 *
 * @author SSheypak
 */
public class EntityReflector {

    public static <T extends Entity> boolean setValue(T entity, String name, String value) throws DataInputException{
        if(entity == null){
            throw new DataInputException("Свойство не может быть записано, т.к. объекта не существует.");
        }
        System.out.println("setValue -> entity["+entity.getClass().getSimpleName()+"] name["+name+"] value["+value+"]");
        try{
            BeanInfo info = Introspector.getBeanInfo( entity.getClass() );
            for ( PropertyDescriptor pd : info.getPropertyDescriptors() ){
                System.out.println("pd.getName["+pd.getName()+"]");
                if(pd.getName().equals(name)){
                    pd.getWriteMethod().invoke(entity, value);
                    return true;
                }
            }
        }catch(Exception e){
            System.out.println("Error while setting property["+name+"] with value["+value+"] for bean ["+entity.getClass().getName()+"]. Message: " + e.getMessage());
            e.printStackTrace();

        }
        return false;
    }
}
